package com.ruoyi.web.controller.business;

import com.github.xiaoymin.knife4j.annotations.ApiSupport;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.text.Convert;
import com.ruoyi.common.enums.PrefixEnum;
import com.ruoyi.common.utils.GenerateCodeUtil;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.framework.config.ServerConfig;
import com.ruoyi.framework.web.service.SysLoginService;
import com.ruoyi.generator.domain.GenTable;
import com.ruoyi.generator.service.IGenTableService;
import com.ruoyi.system.domain.SysFileInfo;
import com.ruoyi.system.service.ISysFileInfoService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@ApiSupport(order = 9997)
@Api(tags = "内部常用接口")
@RestController
@RequestMapping("/test/a3")
public class Example3Controller extends BaseController {
    @Autowired
    private ServerConfig serverConfig;
    @Autowired
    private ISysFileInfoService sysFileInfoService;

    @ApiOperation("后端内部测试上传（登录才能用）")
    @PostMapping("/uploadneibu")
    public AjaxResult uploadneibu(@RequestPart MultipartFile file) {
        try {
            // 上传文件路径
            String filePath = RuoYiConfig.getUploadPath();
            // 上传并返回新文件名称
            String fileName = FileUploadUtils.upload(filePath, file);
            String url = serverConfig.getUrl() + fileName;
            AjaxResult ajax = AjaxResult.success();
            ajax.put("url", url);
            ajax.put("fileName", fileName);
            ajax.put("newFileName", FileUtils.getName(fileName));
            ajax.put("originalFilename", file.getOriginalFilename());

            SysFileInfo sysFileInfo = new SysFileInfo();
            sysFileInfo.setOriginalName(file.getOriginalFilename());
            sysFileInfo.setUrl(fileName);
            sysFileInfo.setExtName(file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1));
            sysFileInfoService.save(sysFileInfo);

            ajax.put("id", sysFileInfo.getId());
            return ajax;
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
    }

    @Autowired
    private SysLoginService loginService;

    @ApiOperation("一键登录")
    @GetMapping("/onKeyLogin")
    public String onKeyLogin() {
        return loginService.loginByApp("admin", "admin123");
    }

    @Autowired
    private IGenTableService genTableService;

    /**
     * 生成代码.zip
     */
    @ApiOperation("生成代码（一键下载）（登录才能用）")
    @GetMapping(value = "/downloadZip/{tableName}", produces = MediaType.APPLICATION_OCTET_STREAM_VALUE )
    public void downloadZip(HttpServletResponse response, @PathVariable("tableName") String tableName) throws IOException
    {
        List<GenTable> genTables = genTableService.selectDbTableListByName(tableName);
        if (genTables.isEmpty()){
            // 查询表信息
            String[] tableNames = Convert.toStrArray(tableName);
            List<GenTable> tableList = genTableService.selectDbTableListByNames(tableNames);
            genTableService.importGenTable(tableList);
        }else if (genTables.size() == 1){
            genTableService.synchDb(tableName);
        }

        byte[] data = genTableService.downloadCode(tableName);
        genCode(response, data, tableName);
    }

    /**
     * 生成zip文件
     */
    private void genCode(HttpServletResponse response, byte[] data, String tableName) throws IOException
    {
        response.reset();
        response.addHeader("Access-Control-Allow-Origin", "*");
        response.addHeader("Access-Control-Expose-Headers", "Content-Disposition");
        response.setHeader("Content-Disposition", "attachment;filename=genCode_"+ tableName + "_" + System.currentTimeMillis() + ".zip");
        response.addHeader("Content-Length", "" + data.length);
        IOUtils.write(data, response.getOutputStream());
    }

    @Autowired
    private GenerateCodeUtil generateCodeUtil;

    @ApiOperation("唯一编号生成器")
    @GetMapping("/orderId")
    public String orderId() {
        return generateCodeUtil.generateNumber(PrefixEnum.Order);
    }
}